package textPack;

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

public class Text4 {
	public static WindowButton win; 
	public static void main(String args[]) {
		win = new WindowButton("猜数字");
	}
}

//计时器
class MyTimer extends TimerTask {

	private Timer timer;
	public int time;

	MyTimer() {

	}

	MyTimer(Timer timer, int time) {

		this.time = time;
		this.timer = timer;
	}

	public void run() {
		WindowButton.inputTime.setText(""+time);
		if(time==0) {
			
			JOptionPane.showMessageDialog(Text4.win, "时间到，你输了");
			System.exit(10);
		}
		this.time--;

		if (this.time < 0) {
			this.timer.cancel();
		}
	}
}

class WindowButton extends JFrame implements ActionListener {
	
	int number;
	JLabel hintLabel, timeLabel;
	static JTextField inputGuess, inputTime=new JTextField("30",10);
	JButton buttonGetNumber, buttonEnter;

	WindowButton(String s) {
		super(s);
		addWindowListener(new WindowAdapter() { // 匿名类的实例监视窗口事件
			public void windowClosing(WindowEvent e) {
				dispose();
			}
		});
		setLayout(new FlowLayout());
		buttonGetNumber = new JButton("得到一个随机数");
		add(buttonGetNumber);
		hintLabel = new JLabel("输入你的猜测：", JLabel.CENTER);
		hintLabel.setBackground(Color.cyan);
		inputGuess = new JTextField("0", 10);

		Timer t = new Timer();
		int s1 = 30;
		MyTimer mt = new MyTimer(t, s1);
		t.scheduleAtFixedRate(mt, 0, 1000);

	
		
		timeLabel = new JLabel("	在30秒内完成:", JLabel.CENTER);
		add(hintLabel);
		add(inputGuess);
		add(inputTime);
		add(timeLabel);

		buttonEnter = new JButton("确定");
		add(buttonEnter);
		buttonEnter.addActionListener(this);
		buttonGetNumber.addActionListener(this);
		setBounds(100, 100, 300, 300);
		setVisible(true);
		validate();
	}

	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == buttonGetNumber) {
			number = (int) (Math.random() * 100) + 1;
			hintLabel.setText("输入你的猜测：");
		} else if (e.getSource() == buttonEnter) {
			int guess = 0;
			try {
				guess = Integer.parseInt(inputGuess.getText());
				if (guess == number) {
					hintLabel.setText("猜对了！");
				} else if (guess > number) {
					hintLabel.setText("猜大了！");
					inputGuess.setText(null);
				} else if (guess < number) {
					hintLabel.setText("猜小了！");
					inputGuess.setText(null);
				}
			} catch (NumberFormatException event) {
				hintLabel.setText("请输入数字字符");
			}
		}
	}

}